/**
 * 列维护
 */
import React, { Component } from 'react';
import { Table, Button, Checkbox, message, Select, Input } from 'antd';
import { $http } from '../../containers/config/https';
import store from 'store';

const Option = Select.Option;
let userData;
class ColumnConfig extends Component {
  constructor(props) {
    super(props);
    userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    this.state = {
      compontName: '001',
      type: "",        //按用户保存
      typeDataID: "",
      authList: [],
      typeOfData: [],
      columnsC: [{
        title: '已配置',
        dataIndex: 'controlFlag',
        width: '80px',
        key: 'controlFlag',
        align: 'center',
        render: (text, record, index) => {
          return record.editor ? (
            <Input style={{ width: '95%' }} value={text} onChange={this.onChange.bind(this, record, 'controlFlag')}></Input>
          ) : text
        },
      }, {
        title: 'code',
        dataIndex: 'code',
        width: '150px',
        key: 'code',
        align: 'center',
        render: (text, record, index) => {
          return record.editor ? (
            <Input style={{ width: '95%' }} value={text} onChange={this.onChange.bind(this, record, 'code')}></Input>
          ) : text
        },
      }, {
        title: userData.language == "EN" ? "descripts" : '列名',
        dataIndex: 'columnName',
        width: '170px',
        key: 'columnName',
        render: (text, record, index) => {
          return (
            <Input style={{ width: '95%' }} value={text} onChange={this.onChange.bind(this, record, 'columnName')}></Input>
          )
        },
      }, {
        title: userData.language == "EN" ? "enDescripts" : '英文描述',
        dataIndex: 'enDescripts',
        width: '170px',
        key: 'enDescripts',
        render: (text, record, index) => {
          return (
            <Input style={{ width: '95%' }} value={text} onChange={this.onChange.bind(this, record, 'enDescripts')}></Input>
          )
        },
      }, {
        title: userData.language == "EN" ? "width" : '列宽',
        dataIndex: 'width',
        width: '90px',
        key: 'width',
        render: (text, record, index) => {
          return (
            <Input style={{ width: '95%' }} value={text} onChange={this.onChange.bind(this, record, 'width')}></Input>
          )
        },
      }, {
        title: userData.language == "EN" ? "align" : '对齐方式',
        dataIndex: 'align',
        width: '120px',
        key: 'align',
        render: (text, record, index) => {
          return (
            <Select style={{ width: '90%' }} value={text} onChange={this.onSelect.bind(this, record, 'align')}>
              <Option value="L" key="L">{userData.language == "EN" ? "left" : '左对齐'}</Option>
              <Option value="C" key="C">{userData.language == "EN" ? "center" : '居中'}</Option>
              <Option value="R" key="R">{userData.language == "EN" ? "right" : '右对齐'}</Option>
            </Select>
          )
        },
      }, {
        title: userData.language == "EN" ? "display" : '显示',
        key: 'displayFlag',
        dataIndex: 'displayFlag',
        width: '60px',
        align: 'center',
        render: (text, record, index) => {
          var displayFlag = record.displayFlag
          if (displayFlag === "Y") {
            displayFlag = true
          } else {
            displayFlag = false
          }
          return (
            <Checkbox checked={displayFlag} onChange={this.CheckOnChange.bind(this, record, index, 'displayFlag')}></Checkbox>
          )
        },
      }, {
        title: userData.language == "EN" ? "export" : '导出',
        dataIndex: 'exportFlag',
        key: 'exportFlag',
        width: '60px',
        align: 'center',
        render: (text, record, index) => {
          var exportFlag = record.exportFlag
          if (exportFlag === "Y") {
            exportFlag = true
          } else {
            exportFlag = false
          }
          return (
            <Checkbox checked={exportFlag} onChange={this.CheckOnChange.bind(this, record, index, 'exportFlag')}></Checkbox>
          )
        }
      }, {
        title: userData.language == "EN" ? "print" : '打印',
        dataIndex: '',
        key: 'pringFlag',
        width: '60px',
        align: 'center',
        render: (text, record, index) => {
          var pringFlag = record.pringFlag
          if (pringFlag === "Y") {
            pringFlag = true
          } else {
            pringFlag = false
          }
          return (
            <Checkbox checked={pringFlag} onChange={this.CheckOnChange.bind(this, record, index, 'pringFlag')}></Checkbox>
          )
        }
      }],
      columnsB: [{
        title: 'code',
        dataIndex: 'code',
        width: '150px',
        key: 'code',
        render: (text, record, index) => {
          return record.editor ? (
            <Input style={{ width: '95%' }} value={text} onChange={this.onChange.bind(this, record, 'code')}></Input>
          ) : text
        }
      }, {
        title: userData.language == "EN" ? "buttonName" : '按钮名称',
        dataIndex: 'columnName',
        width: '200px',
        key: 'columnName',
        render: (text, record, index) => {
          return (
            <Input style={{ width: '95%' }} value={text} onChange={this.onChange.bind(this, record, 'columnName')}></Input>
          )
        },
      }, {
        title: userData.language == "EN" ? "buttonEnName" : '英文描述',
        dataIndex: 'enDescripts',
        width: '200px',
        key: 'enDescripts',
        render: (text, record, index) => {
          return (
            <Input style={{ width: '95%' }} value={text} onChange={this.onChange.bind(this, record, 'enDescripts')}></Input>
          )
        },
      }, {
        title: userData.language == "EN" ? "display" : '是否隐藏',
        key: 'displayFlag',
        dataIndex: 'displayFlag',
        width: '',
        render: (text, record, index) => {
          var displayFlag = record.displayFlag
          if (displayFlag === "Y") {
            displayFlag = true
          } else {
            displayFlag = false
          }
          return (
            <Checkbox checked={displayFlag} onChange={this.CheckOnChange.bind(this, record, index, 'displayFlag')}></Checkbox>
          )
        }
      }],
      columns: [],
      data: [],
      selectedRowKeys: [],
      configType: "C",
    }
  }

  //文本内容改变时触发
  onChange = (record, field, e) => {
    record[field] = e.target.value;
    this.forceUpdate();
  }

  //下拉框内容改变时触发
  onSelect = (record, field, value) => {
    record[field] = value;
    this.forceUpdate();
  }

  //复选框勾选触发
  CheckOnChange = (record, index, field) => {
    if (record[field] === "Y") {
      record[field] = "N"
    } else {
      record[field] = "Y"
    }
    var data = this.state.data
    data[index] = record
    this.setState({ data: data })
  }

  getData = (compontName, configType) => {
    if (!compontName) {
      this.setState({ data: [] });
      return;
    }
    let data = {
      params: [{
        compontName: compontName,
        type: this.state.type,
        saveType: this.state.type,
        language: userData.language,
        typeDataID: this.state.typeDataID
      }]
    };
    let columns = this.state.columnsB;
    if (configType === "C") {
      columns = this.state.columnsC;
    }
    $http.post('urlS', this, {
      code: "01040210",
      data: data,
      success: function (res) {
        this.setState({
          compontName: compontName,
          configType: configType,
          columns: columns,
          data: res.result.data,
          // type: res.defaultType,
        })
      }
    });
  }

  // 保存列权限
  saveData = () => {
    let data = {
      params: [{
        tableData: this.state.data,
        updateUser: userData.userID,
        type: this.state.type,
        language: userData.language,
        compontName: this.state.compontName,
        typeDataID: this.state.typeDataID
      }]
    };
    $http.post('urlDeault', this, {
      code: "01040039",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('保存成功！');
          // this.props.onCancel();
          this.getData(this.state.compontName, this.state.configType);
          /**清空选中行 */
          this.setState({ selectedRowKeys: "" })
        }
      }
    });
  }

  // 删除列权限
  delData = () => {
    let data = {
      params: [{
        updateUser: userData.userID,
        type: this.state.type,
        compontName: this.state.compontName,
      }]
    };
    $http.post('urlDeault', this, {
      code: "01040101",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('删除成功！');
          this.getData(this.props.compontName, this.props.configType);
        }
      }
    });
  }

  componentDidMount() {
    this.props.onRef(this);
    this.reloadData();
  }

  // componentWillReceiveProps(nextprops) {
  //   if (nextprops.visible) {
  //     this.setState({
  //       columns: [],
  //       data: [],
  //       selectedRowKeys: [],
  //     }, () => {
  //       this.getEditAuth();
  //       this.getData(nextprops.compontName, nextprops.configType);
  //     })
  //   }
  // }

  // 获取编辑权限
  getEditAuth = () => {
    let data = { params: [{}] };
    $http.post('urlDeault', this, {
      code: "01040094",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ authList: res.result.authList })
          let defaultTypeCode = "H"
          res.result.authList.forEach(element => {
            if (element.value === "C") defaultTypeCode = "C";
          });
          this.setState({ type: defaultTypeCode });
          /**不是公共可给类型数据下拉框数据 */
          if (defaultTypeCode !== "C") {
            this.setState({
              typeOfData: this.props.typeOfData[defaultTypeCode],
              typeDataID: this.props.typeOfData[defaultTypeCode][0].id,
            })
          }
        }
      }
    });
  }

  reloadData = () => {
    this.setState({
      columns: [],
      data: [],
      selectedRowKeys: [],
    }, () => {
      this.getEditAuth();
      this.getData(this.props.compontName, this.props.configType);
    })
  }

  selectChage = (value) => {
    this.setState({
      typeDataID: value,
    },
      () => {
        this.getData(this.state.compontName, this.state.configType);
      });
  }

  //选择权限类型
  selectTypeChage = (value) => {
    console.dir(this.props.typeOfData);
    console.dir(this.props.typeOfData[value]);
    this.setState({
      type: value,
      selectedRowKeys: [],
      typeOfData: this.props.typeOfData[value],
      typeDataID: this.props.typeOfData[value][0].id,
    });
  }

  //上移
  handleUp = () => {
    var keys = this.state.selectedRowKeys
    var data = this.state.data
    var newKeys = []
    keys = keys.sort(function (m, n) {
      if (m < n) return -1
      else if (m > n) return 1
      else return 0
    });
    for (var i = 0; i < keys.length; i++) {
      if (keys[i] === 0) {
        newKeys.push(keys[i])
        continue
      }
      var curRowData = data[keys[i]]
      var curRowKey = curRowData.key
      var upRowData = data[keys[i] - 1]
      var upRowKey = upRowData.key
      upRowData.key = curRowKey
      curRowData.key = upRowKey
      data[keys[i]] = upRowData
      data[keys[i] - 1] = curRowData
      newKeys.push(keys[i] - 1)
    }
    this.setState(
      {
        data: data,
        selectedRowKeys: newKeys
      }
    )
  }

  //下移
  handleDown = () => {
    var keys = this.state.selectedRowKeys
    var data = this.state.data
    var newKeys = []
    keys = keys.sort(function (m, n) {
      if (m < n) return -1
      else if (m > n) return 1
      else return 0
    });
    for (var i = keys.length - 1; i >= 0; i--) {
      if (keys[i] === data.length - 1) {
        newKeys.push(keys[i])
        continue
      }
      var curRowData = data[keys[i]]
      var upRowData = data[keys[i] + 1]
      var curRowKey = curRowData.key
      var upRowKey = upRowData.key
      upRowData.key = curRowKey
      curRowData.key = upRowKey
      data[keys[i]] = upRowData
      data[keys[i] + 1] = curRowData
      newKeys.push(keys[i] + 1)
    }
    this.setState(
      {
        data: data,
        selectedRowKeys: newKeys
      }
    )
  }

  //增加列
  addColumn = () => {
    if (this.state.type != "C") {
      return;
    }
    let data = this.state.data;
    let obj = {};
    obj.ID = "";
    obj.code = "";
    obj.align = "";
    obj.columnName = "";
    obj.displayFlag = "";
    obj.enDescripts = "";
    obj.exportFlag = "";
    obj.pringFlag = "";
    obj.type = this.state.type;
    obj.width = "";
    obj.editor = true;
    data.push(obj);
    this.setState({
      data: data
    })
  }

  render() {
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRowKeys: selectedRowKeys })
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
      selectedRowKeys: this.state.selectedRowKeys
    };

    return (
      <div style={{ height: '100%', width: '100%' }}>
        <div className="table-operations" style={{ marginBottom: 12 }}>
          <Select
            allowClear
            showSearch
            optionFilterProp="seachprop"
            value={this.state.type}
            className="common-query-input"
            onChange={this.selectTypeChage}
          >
            {React.$SelectOptions(this.state.authList, 'value')}
          </Select>
          <Select
            allowClear
            showSearch
            optionFilterProp="seachprop"
            value={this.state.typeDataID}
            className="common-query-input"
            style={{ width: '200px' }}
            onChange={this.selectChage}
          >
            {React.$SelectOptions(this.state.typeOfData)}
          </Select>
          <Button ghost type="primary" onClick={this.getData.bind(this, this.state.compontName, "C")} style={{ marginRight: '12px' }}>{userData.language == "EN" ? "column" : "列"}</Button>
          <Button ghost type="primary" onClick={this.getData.bind(this, this.state.compontName, "B")} style={{ marginRight: '12px' }}>{userData.language == "EN" ? "button" : "按钮"}</Button>
          <Button ghost type="primary" onClick={this.handleUp} style={{ marginRight: '12px' }}>{userData.language == "EN" ? "moveUP" : "向上移动"}</Button>
          <Button ghost type="primary" onClick={this.handleDown} style={{ marginRight: '12px' }}>{userData.language == "EN" ? "moveDown" : "向下移动"}</Button>
          <Button type="primary" disabled={this.state.type != "C"} onClick={this.addColumn} style={{ marginRight: '12px' }}>{userData.language == "EN" ? "add" : "添加"}</Button>
          <Button type="primary" onClick={this.saveData} style={{ marginRight: '12px' }}>{userData.language == "EN" ? "save" : "保存"}</Button>
          <Button type="danger" onClick={this.delData}>{userData.language == "EN" ? "deleteCurrent" : "删除当前配置"}</Button>
        </div>
        <Table
          rowSelection={rowSelection}
          columns={this.state.columns}
          dataSource={this.state.data}
          pagination={false}
          bordered
          rowKey={(data, index) => {
            return index
          }}
          style={{ height: store.getState().tableHeight.y + 100 + 'px' }}
          scroll={{ x: 980, y: store.getState().tableHeight.y + 50 }}
        />
      </div >
    );
  }
}

export default ColumnConfig;  